'''
Created on Jan 6, 2011

@author: Rafael Nunes
'''
from django.shortcuts import render_to_response, render
from jinbu.core.models import Promocao, AssinanteNews, Estado
from django.views.decorators.csrf import csrf_protect
from jinbu.core.forms import EmpresaForm
from django.http import HttpResponse
from django.contrib.gis.utils.geoip import GeoIP
from django.utils import simplejson
from jinbu.core.util import str_utils

@csrf_protect
def index(request):
    promos = Promocao.objects.get_for_index()
    list_p1 = promos.get(promos.keys()[0])
    list_p2 = promos.get(promos.keys()[1])
    list_p3 = promos.get(promos.keys()[2])
    c_tits = {'tit1':promos.keys()[0], 'tit2':promos.keys()[1], 'tit3':promos.keys()[2]}
    g = GeoIP()
    ip = request.META['REMOTE_ADDR']
    ip = '189.54.111.22' #TODO REMOVE
    uf_user = str_utils.to_unicode_or_bust(g.city(ip)['city'], encoding='iso-8859-1').encode('utf8')
    return render(request, 'index.xhtml', locals())

@csrf_protect
def add_user(request):
    if request.method == 'POST':
        pass
    else:
        return render(request, 'cadastroFisico.xhtml', locals())
@csrf_protect
def add_empresa(request):
    if request.method == 'POST':
        form = EmpresaForm(request.POST)
        empresa = form.save()
        return render_to_response('navEmpresa.xhtml', locals())
    else:
        return render(request, 'cadastroEmpresa.xhtml', locals())
 

def nav_empresa(request):
    return render_to_response('navEmpresa.xhtml', locals())

def news_add(request):
    m = request.POST['mail']
    if not AssinanteNews.objects.filter(mail=m):
        g = GeoIP()
        ip = request.META['REMOTE_ADDR']
        ip = '189.54.111.22' #TODO REMOVE
        uf_user = g.city(ip)['city']
        assinante = AssinanteNews(mail=m, uf=uf_user)
        assinante.save()
    return HttpResponse()

def get_estados(request):
    estados = Estado.objects.all()
    lista = []
    for e in estados:
        lista.append({"nome": e.nome, "sigla":e.sigla})
    json_data = simplejson.dumps(lista)
    return HttpResponse(json_data)
    
def set_local(request):
    uf_user = request.GET['cmb_estado']
    return render(request, 'index.xhtml', locals())


